<?php
/**
 * Created by WuYe.
 * User: '常志明'
 * Date: 2018-10-11 16:40
 * 考核评分
 */

namespace app\index\controller;


class RecoScore
{
    //考核评分
    const recoscore = [
        'userId'=>'',       //usermange(id)
        'position_id'=>'',  //职位id jurisdiction
        'name'=>'',         //名字
        'total'=>'0',        //总分
        'rateKinds'=>[],    //[ {kindName: '作业单', // 作业类型number: '150', // 完成单数value: 4 // 分值}，
        'datetime'=>'',     //年
    ];

    public static function getData($where, $one = true, $table = 'recoscore')
    {
        return ($one == true) ? getFirst(mongo($table)->where($where)->select()) : mongo($table)->where($where)->select();
    }
    public static function setData($where, $data, $table = 'recoscore')
    {
        mongo($table)->where($where)->update($data);
    }
    public static function insertData($data, $table = 'recoscore')
    {
        mongo($table)->insert($data);
        return mongo($table)->getLastInsID();
    }
    public static function deleteData($where, $table = 'recoscore')
    {
        mongo($table)->where($where)->delete();
    }

    /**
     * 获取所有考核评分
     */
    public static function appgetStaffScoreByPositon()
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $returnJurisdictions = [];
        $jurisdictions =  Jurisdiction::getPositionsDb()['data'];
        foreach ($jurisdictions as $jurisdiction) {
            $rerult = self::getStaffScoreByPositon($jurisdiction['id'])['data'];
            array_push($returnJurisdictions, ['id'=>$jurisdiction['id'], 'position'=>$jurisdiction['position'], 'staffScores'=>$rerult]);
        }
        return RD(SUCCESS, $returnJurisdictions);
    }
    /**
     * 根据岗位获取员工及员工评分信息
     * @param string $positionId  员工岗位
     */
    public static function getStaffScoreByPositon($positionId = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $positionId = (empty($positionId) && $positionId !== 0) ? input('positionId', '-1') : $positionId;
        $userList = User::getData(['position_id'=>$positionId], false);  //获取该岗位所有用户

        foreach ($userList as $user)
        {
            $rateKinds = [];
            //作业单
            $jobCount = count(JobCard::getData(['receiverId'=>cookie('userId'),'completeTime'=>['>=', date('Y')]], false));
            array_push($rateKinds, ['kindName'=>'作业单', 'number'=>$jobCount, 'value'=>'0']);
            //学习培训
            array_push($rateKinds, ['kindName'=>'学习培训', 'number'=>'0', 'value'=>'0']);
            //故障报修
            $malCount = count(Malfunction::getData(['receiverPeople'=>cookie('userId'), 'maintainDatetime'=>['>=', date('Y')]], false));  //故障报修单
            array_push($rateKinds, ['kindName'=>'故障报修', 'number'=>$malCount, 'value'=>'0']);

            $result = self::getData(['userId'=>$user['id'], 'datetime'=>date('Y')]);
            if(empty($result)) {  //添加信息
                $insertData = [
                    'userId'=>$user['id'],
                    'name'=>$user['username'],
                    'total'=>'0',
                    'datetime'=>date('Y'),
                    'rateKinds'=>$rateKinds,
                    'position_id'=>$positionId,
                ];
                self::insertData($insertData);
            } else {
                //更新单数
                $result = self::getData(['userId'=>$user['id'], 'datetime'=>date('Y')]);
                $rateKinds = $result['rateKinds'];
                foreach ($rateKinds as $key=>$kind)
                {
                    switch ($kind['kindName'])
                    {
                        case '作业单':
                            $rateKinds[$key]['number'] = $jobCount;
                            break;
                        case '学习培训':
                            break;
                        case '故障报修':
                            $rateKinds[$key]['number'] = $malCount;
                            break;
                    }
                }
                self::setData(['userId'=>$user['id'], 'datetime'=>date('Y')], ['rateKinds'=>$rateKinds]);
            }
        }
        $data = self::getData(['position_id'=>$positionId, 'datetime'=>date('Y')], false);  //获取本职位本年所有员工评分
        //添加头像
        foreach ($data as $key=>$userdata) {
            $data[$key]['img'] = User::getData(['id'=>$userdata['userId']])['img'];
            renameArray($data[$key], 'userId', 'id');  //重命名
        }
        return RD(SUCCESS, $data);
    }

    /**
     * 为员工考核评分
     * @param array $staff  用户及评分信息
     */
    public static function scoreForStaff($staff = [])
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $staff = input('staff/a', []);
        if(empty($staff)) return RD(PARA_NOT_NULL);

        foreach ($staff as $user) {
            self::setData(['userId'=>$user['id']], ['total'=>$user['total'], 'rateKinds'=>$user['rateKinds']]);
        }
        return RD(SUCCESS);
    }

    /**
     * 获取年度排行
     */
    public static function getRankingList()
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $data = self::getData(['datetime'=>date('Y')], false);

        $my_sort = function ($a,$b) {
            return strcmp($a['total'], $b['total']);
        };
        usort($data, $my_sort);  //排序
        $returnData = [];

        $jurisdictions =  Jurisdiction::getPositionsDb()['data'];
        foreach ($jurisdictions as $jurisdiction) {
            foreach ($data as $key=>$value) {
                if($jurisdiction['id'] == $value['position_id']) {
                    $img = User::getData(['id'=>$value['userId']])['img'] ?? '';
                    array_push($returnData, ['id'=>$value['userId'], 'name'=>$value['name'], 'total'=>$value['total'],
                        'positionName'=>$jurisdiction['position'], 'rateKinds'=>$value['rateKinds'], 'img'=>$img]);
                    break;
                }
            }
        }
        return RD(SUCCESS, $data);
    }

}